import sendCode, { valueOfOpTypes } from '@src/apis/send_code';
import { validatePhoneNumber } from '@src/utils';
import { message } from 'antd';
import { useEffect, useReducer, useState } from 'react';

// 强制更新
export const useForceRender = () => {
  const [, dispatchUpdate] = useReducer((num) => num + 1, 0);
  return dispatchUpdate;
};

// 发送验证码
export const useSendSmsCode = () => {
  const [countdown, setCountdown] = useState(0);
  const [loading, setLoading] = useState(false);

  const handleSendSmsCode = async (
    phoneNumber: string,
    type: valueOfOpTypes,
  ) => {
    if (!validatePhoneNumber(phoneNumber) || !phoneNumber) {
      message.error('请先输入正确的手机号');
      return;
    }

    if (countdown) {
      message.error('发送太频繁了，请稍后重试');
      return;
    }

    setLoading(true);

    // 调用发送短信验证码的 API
    try {
      await sendCode(phoneNumber, type);
      message.success('验证码发送成功');
      setCountdown(60);
    } catch (err: any) {
      message.error(err.msg);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    let timer;
    if (countdown > 0) {
      timer = setInterval(() => {
        setCountdown((prevCountdown) => prevCountdown - 1);
      }, 1000);
    }
    return () => clearInterval(timer);
  }, [countdown]);

  return {
    countdown,
    setCountdown,
    loading,
    setLoading,
    handleSendSmsCode,
  };
};
